import { SysOrder } from "../../GameDef";
import { IECSFilter } from "../../lib/kgame/ecs/ECSFilter";
import { ECSSys } from "../../lib/kgame/ecs/ECSSys";
import { MathUtil } from "../../lib/kgame/util/MathUtil";
import { MoveCmp } from "../cmp/MoveCmp";

/**
 * 移动系统
 */
export class MoveSys extends ECSSys {

    get updateOrder(): number {
        return SysOrder.move;
    }

    get ifilter(): IECSFilter {
        return { includeOne: [MoveCmp] };
    }

    onUpdate(): void {
        this.getCmps(MoveCmp).forEach(move => {
            if (move.toDir !== move.moveDir) {
                const diff = MathUtil.radDiff(move.moveDir, move.toDir);
                const add = move.rotSpd * this.scene.dt;
                if (add < Math.abs(diff)) {
                    move.moveDir += Math.sign(diff) * add;
                } else {
                    move.moveDir = move.toDir;
                }
            }

            //冲刺速度
            const sprintSpdMax = move.moveSpd;
            if (move.isSprint) {
                if (move.sprintSpd < sprintSpdMax) {
                    const addSpd = move.moveSpd * this.scene.dt * 2;
                    move.sprintSpd = Math.min(sprintSpdMax, move.sprintSpd + addSpd);
                }
            } else if (move.sprintSpd > 0) {
                const reduceSpd = move.moveSpd * this.scene.dt * 4;
                move.sprintSpd = Math.max(0, move.sprintSpd - reduceSpd);
            }

            move.pos.moveRad(move.moveDir, (move.moveSpd + move.sprintSpd) * this.scene.dt);
        });
    }

}